<?php

class Ext_Acl_Build
{
    public $acl;
    
    public function __construct()
    {
        $this->acl = new Zend_Acl();
    }
    
    public function build($roleId)
    {
        if(!$roleId){
            return $this;
        }
        
        $roleFamilies = array();
        App_Model_Role::getInstance()->getRoleFamilies($roleId, $roleFamilies);
        $roleFamilies = array_reverse($roleFamilies);
        //print_r($roleFamilies);
        for($i=0;$i<count($roleFamilies);$i++)
        {
            $_roleId  = $roleFamilies[$i]['id'];
            $parentId = $roleFamilies[$i]['parentId'];
            $resourceName = "";
                    
            if($parentId){
                $this->acl->addRole(new Zend_Acl_Role($_roleId), $parentId);
            }else{
                $this->acl->addRole(new Zend_Acl_Role($_roleId));
            }

            $resource = array();
            $controlAll = App_Model_DbTable_Acl_Control::getInstance()->getControlAllByRoleId($_roleId);
            for($ii=0;$ii<count($controlAll);$ii++)
            {
                $accessId  = $controlAll[$ii]['accessId'];
                $accessRow = App_Model_DbTable_Acl_Access::getInstance()->getRowById($accessId);
                if(!$accessRow)
                {
                    continue;
                }
                
                $aclResource = $accessRow['aclResource'];
                if(!$aclResource)
                {
                    $aclResource = null;
                }
                if(!$this->acl->has($aclResource))
                {
                    $resource[] = $aclResource;
                    $this->acl->add(new Zend_Acl_Resource($aclResource));
                }
                
                $aclAction = $accessRow['aclAction'];
                if($aclAction == '')
                {
                    $aclAction = null;
                }
                
                if($controlAll[$ii]['controlType'] > 1)
                {
                    $this->acl->deny(array($_roleId), $aclResource, $aclAction);
                }
                else if($controlAll[$ii]['controlType'] == 1)
                {
                    $this->acl->allow(array($_roleId), $aclResource, $aclAction);
                }
            }
        }
        
        return $this;

    }
}
